<template>
  <el-row>
    <el-col :span="24" style="margin: 24px;">
      <el-form ref="ruleFormRef" :rules="rules" :model="formData" label-width="auto" style="max-width: 80vw">
        <!-- Warehouse Name -->
        <input-widget-web 
          v-model="formData.name" 
          label="仓库名称" 
          prop="name" 
          :disabled="!isEditMode"
          :rules="[{ required: true, message: '请输入仓库名称', trigger: 'blur' }]">
        </input-widget-web>

        <!-- Contact Person -->
        <input-widget-web 
          v-model="formData.contactPerson" 
          label="联系人" 
          prop="contactPerson" 
          :disabled="!isEditMode">
        </input-widget-web>

        <!-- Contact Phone -->
        <input-widget-web 
          v-model="formData.contactPhoneNum" 
          label="联系电话" 
          prop="contactPhoneNum" 
          :disabled="!isEditMode">
        </input-widget-web>

        <!-- Address -->
        <input-widget-web 
          v-model="formData.addr" 
          label="仓库地址" 
          prop="addr" 
          :disabled="!isEditMode"
          :remarkMode="true">
        </input-widget-web>

        <!-- Status -->
        <el-form-item label="启用状态" prop="enabled">
          <el-switch 
            v-model="formData.enabled" 
            :disabled="!isEditMode" 
            active-text="启用" 
            inactive-text="停用" />
        </el-form-item>

        <!-- Lock Status -->
        <el-form-item label="锁定状态" prop="locked" v-if="formData.locked !== undefined">
          <el-switch 
            v-model="formData.locked" 
            :disabled="true" 
            active-text="锁定" 
            inactive-text="未锁定" />
        </el-form-item>

        <!-- Remark -->
        <input-widget-web 
          v-model="formData.remark" 
          label="备注" 
          prop="remark" 
          :disabled="!isEditMode"
          :remarkMode="true">
        </input-widget-web>

        <!-- Action Buttons -->
        <el-form-item style="margin-left: 70px;">
          <el-button @click="handleSave(ruleFormRef)" v-if="isEditMode" type="primary">保存</el-button>
          <el-button @click="toggleEditMode(false)" v-if="isEditMode">取消</el-button>
          <el-button @click="removeWareHouse()" v-if="!isEditMode" type="danger">删除</el-button>
          <el-button @click="toggleEditMode(true)" v-if="!isEditMode" type="primary">编辑</el-button>
          <el-button @click="closePage()" v-if="!isEditMode">返回</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import { ElMessage } from 'element-plus'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { WareHouse } from '../../public/engine/inventory/warehouse'
import { Util } from '../../public/utils/util'
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue'
import { NetworkParser } from '../../public/network/communicationConverter'
import TabUtil from '@/plugins/tab'
import EventBus from '../../public/engine/ipc/eventBus'
import { updateOrCreateWareHouse, removeWareHouse } from "../../public/network/api"
import { ActionResult, ActionResultType } from '../../public/engine/common/actionResult'
import { Engine } from '../../public/engine/engine'

export default {
  name: 'warehouseDetail',
  components: {
    InputWidgetWeb
  },
  data() {
    return {
      isEditMode: false,
      warehouse: new WareHouse({}),
      formData: {},
      originalWarehouse: null,
      inventoryUiAction: new InventoryUiAction(),
      retValue: null
    }
  },
  methods: {
    syncFormData() {
      this.formData = {
        name: this.warehouse.name,
        contactPerson: this.warehouse.contactPerson,
        contactPhoneNum: this.warehouse.contactPhoneNum,
        addr: this.warehouse.addr,
        enabled: this.warehouse.enabled,
        locked: this.warehouse.locked,
        remark: this.warehouse.remark
      };
    },
    
    fillWithFormData() {
      this.warehouse.name = this.formData.name;
      this.warehouse.contactPerson = this.formData.contactPerson;
      this.warehouse.contactPhoneNum = this.formData.contactPhoneNum;
      this.warehouse.addr = this.formData.addr;
      this.warehouse.enabled = this.formData.enabled;
      this.warehouse.locked = this.formData.locked;
      this.warehouse.remark = this.formData.remark;
    },

    async fetchData(warehouseId) {
      try {
        const res = await this.inventoryUiAction.getWarehouseDetail(warehouseId)
        if (res) {
          this.warehouse = res;
          this.syncFormData();
        }
      } catch (error) {
        ElMessage.error('获取仓库详情失败')
        console.error(error)
      }
    },

    closePage() {
      try {
        TabUtil.closePage();
        return;
      } catch (e) {
        console.log('直接关闭失败，尝试替代方案');
      }

      if (window.history.length > 1) {
        window.history.back();
        return;
      }

      window.location.href = '/';
    },

    toggleEditMode(edit) {
      this.isEditMode = edit
      if (!edit) {
        this.syncFormData();
      }
    },

    async removeWareHouse() {
      if (Util.isEmpty(this.warehouse.id)) {
        TabUtil.closePage();
        return;
      }

      try {
        const res = await removeWareHouse({ids:  this.warehouse.id, orgId: Engine.profile.org.orgId});
        let reqResult = NetworkParser.parseNetworkResult(res, null);

        if (reqResult.resErr != null) {
          console.error('删除仓库失败', reqResult.resErr);
          ElMessage.error("删除仓库失败:" + reqResult.resErr);
          return;
        }
        else if (reqResult.data != null) {
          ElMessage.success('删除仓库成功');
          this.retValue = new ActionResult({ type: ActionResultType.Del });
          setTimeout(() => {
            console.log("Closing page after deletion");
            TabUtil.closePage();
          }, 1000);
        }
      } catch (error) {
        console.error('删除仓库失败', error);
        ElMessage.error("删除仓库失败:" + error);
      }
    },

    async handleSave() {
      try {
        await this.$refs.ruleFormRef.validate();
        this.fillWithFormData();

        const res = await updateOrCreateWareHouse({wareHouse:this.warehouse});
        const reqResult = NetworkParser.parseNetworkResult(res, null);

        if (reqResult.resErr != null) {
          console.error('提交仓库数据失败', reqResult.resErr);
          ElMessage.error("提交仓库数据失败:" + reqResult.resErr);
          return;
        }
        else if (reqResult.data != null) {
          let type = ActionResultType.None;
          if (Util.isEmpty(this.warehouse.id)) {
            type = ActionResultType.New;
          } else {
            type = ActionResultType.UpdateCommon;
          }

          if (Util.isEmpty(this.warehouse.id)) {
             // 新建仓库没有返回仓库id
            //this.warehouse.id = Util.jsonToString(reqResult.data);
            this.retValue = new ActionResult({ type: type, param: this.warehouse.toCopyJson() });
            ElMessage.success("创建成功!");
            this.isEditMode = false;
            //this.fetchData(this.warehouse.id);
            TabUtil.closePage();
          } else {
            ElMessage.success("更新成功!");
            this.isEditMode = false;
            this.fetchData(this.warehouse.id);
            this.retValue = new ActionResult({ type: type, param: null });
          }
        }
      } catch (error) {
        ElMessage.error('保存仓库失败')
        console.error(error)
      }
    }
  },
  mounted() {
    this.retValue = null;
    const warehouseId = this.$route.params.id || this.$route.query.id;
    this.syncFormData();
    if (warehouseId) {
      this.fetchData(warehouseId)
    } else {
      this.isEditMode = true
    }
  },
  beforeUnmount() {
    if (this.retValue) {
      EventBus.emit('warehouseUpdated', this.retValue.toCopyJson());
      this.retValue = null;
    }
  },
  deactivated() {
    if (this.retValue) {      
      EventBus.emit('warehouseUpdated', this.retValue.toCopyJson())
      this.retValue = null;
    }
  }
}
</script>